import message from '@/ui/message';
import {PageModule} from './PageModule';

class Loader{
    constructor() {
        this.staticModules={};
    }
    //加载静态资源
    loadResources(opts) {
        // let baseUrl=`http://local.mp.cn`;
        const {appId,pagePath,platform,currProjectPath}=opts;
        let viewResources='';
        let styleResources='';
        if(platform=='app'){
            viewResources=currProjectPath+`/apps/${appId}/view.js`;
            styleResources=currProjectPath+`/apps/${appId}/style.css`;

        }else{
            viewResources=currProjectPath+`/view.js`;
            styleResources=currProjectPath+`/style.css`;
        }
        const script=document.createElement('script');
        const link=document.createElement('link');

        Promise.all([
            this.loadScriptFile(script,viewResources),
            this.loadStyleFile(link,styleResources)
        ]).then(()=>{
            // console.log('资源加载完成:',pagePath);
            modRequire(pagePath)
            message.send({
                tppe:'uiResourcesLoaded',
                body:{
                    
                }
            })
        })

    }
    loadStyleFile(link,path){
        return new Promise((resolve,reject)=>{
            
            link.rel='stylesheet';
            link.href=path;
            link.onload=()=>{
                resolve();
            }
            
            document.body.appendChild(link);
        })
    }
    loadScriptFile(script,path){
        return new Promise((resolve,reject)=>{
            
            script.src=path;
            script.onload=()=>{
                resolve();
            }
            
            document.body.appendChild(script);
        })
    }
    createPageModule(mobuleInfo){
        const pageModule=new PageModule(mobuleInfo);
        const {path}=mobuleInfo;
        this.staticModules[path]=pageModule;
    }
    setInitialData(initialData){

        for(let [path,data] of Object.entries(initialData)){
            const staticModule=this.staticModules[path];
            if(!staticModule) {
                continue;
            }

            staticModule.setInitialData(data);
        }
    }
    getModuleByPath(path){
        return this.staticModules[path];
    }
    
}

export default new Loader();